package com.ruoyi.hr.service.impl.changemanage.depchange;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.hr.domain.Authority;
import com.ruoyi.hr.mapper.SkyMsgAlarmMapper;
import com.ruoyi.hr.mapper.changemanage.ChangeManageMapper;
import com.ruoyi.hr.mapper.changemanage.depchange.DepChangeMapper;
import com.ruoyi.hr.service.changemanage.depchange.DepChangeService;
import com.ruoyi.hr.util.BaseResult;
import com.ruoyi.hr.util.ResultEnum;
import com.ruoyi.hr.util.utils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class DepChangeServiceImpl implements DepChangeService {

    @Autowired
    DepChangeMapper depChangeMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SkyMsgAlarmMapper skyMsgAlarmMapper;

    @Autowired
    ChangeManageMapper changeManageMapper;

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<Map<String, Object>> findDepChangeData(Map map, Authority authority) {
        return depChangeMapper.findDepChangeData(map, authority);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<Map<String, Object>> addDepChangeEmp(Map map, Authority authority) {
        return depChangeMapper.addDepChangeEmp(map, authority);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public Map<String, Object> getDepChangeEmpById(String id) {
        Map<String, Object> depChangeEmp = depChangeMapper.getDepChangeEmpById(id);
        String[] files = {"id", "badge", "name", "compName", "depName", "depId", "jobName", "empStatusName",
                "joindate", "WorkCityTitle", "empTypeName", "ReportToName", "WfReportToName", "NewCompName",
                "NewDepName", "NewJobName", "NewWorkcity", "NewEmpType", "NewReportToName", "NewWfReportToName",
                "orgchangetypeTitle", "orgchangeReasonTitle", "salarycompTitle", "EffectDate", "Remark", "newCompid",
                "newDepid", "newJobid", "emptype", "NewReportTo", "NewWfReportTo", "orgchangetype", "orgchangeReason",
                "salarycomp", "NewWorkcityName", "newworkcity"};
        for (int i = 0; i < files.length; i++) {
            if (!depChangeEmp.containsKey(files[i])) {
                depChangeEmp.put(files[i], "");
            }
        }
        return depChangeEmp;
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public int updateDepChange(Map map) {
        return depChangeMapper.updateDepChange(map);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public BaseResult addInternshipChangeEmp(String allEid) {
        //叠加异常信息
        String msgAdd = "";
        try {
            //存储过程sql
            String sql;
            SysUser user = ShiroUtils.getSysUser();
            Map<String, Object> maps = sysUserMapper.selectSkySecUser(user.getLoginName());
            String[] array = allEid.split(",");
            String msg;//异常信息
            for (String s : array) {
                //根据PEID取出人名
                String name = changeManageMapper.getEmpName(s);
                sql = "declare @RetVal varchar(50) exec eSP_ChangeOrgAddEmp " + s + ",1," + maps.get("id").toString() + ",@RetVal output select @RetVal";
                String retVal = depChangeMapper.executeProcedure(sql);
                msg = skyMsgAlarmMapper.getMsgById(retVal);
                if (msg != null) {
                    msgAdd += name + ":" + msg + "\n";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.build(ResultEnum.SERVER_ERROR);
        }
        if ("".equals(msgAdd)) {
            return BaseResult.build(ResultEnum.SUCCESS);
        } else {
            return BaseResult.build(19970926, msgAdd, null);
        }
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public BaseResult procedure(String allId, String procedure) {
        //叠加异常信息
        String msgAdd = "";
        try {
            //存储过程sql
            String sql = "";
            SysUser user = ShiroUtils.getSysUser();
            Map<String, Object> maps = sysUserMapper.selectSkySecUser(user.getLoginName());
            String[] array = allId.split(",");
            String msg;//异常信息
            for (String id : array) {
                //根据id取出人名
                String name = depChangeMapper.getNameById(id);
                if (procedure.equals("eSP_ChangeOrgCheck")) {
                    sql = "declare @RetVal varchar(50) exec eSP_ChangeOrgCheck " + id + "," + maps.get("id").toString() + ",@RetVal output select @RetVal";
                } else if (procedure.equals("eSP_ChangeOrgCancel")) {
                    sql = "declare @RetVal varchar(50) exec eSP_ChangeOrgCancel " + id + "," + maps.get("id").toString() + ",@RetVal output select @RetVal";
                } else if (procedure.equals("eSP_ChangeOrgStart")) {
                    sql = "declare @RetVal varchar(50) exec eSP_ChangeOrgStart " + id + "," + maps.get("id").toString() + ",@RetVal output select @RetVal";
                }
                msg = "";
                List<List<Map<String, Object>>> retVal = depChangeMapper.ExProcedure(sql);
                //如果大小为1直接取出返回值，先判断是否有key,再判断是否为数字执行
                if (retVal.size() == 1) {
                    if (((Map) retVal.get(0)).containsKey("")) {
                        String by = ((Map) retVal.get(0)).get("").toString();
                        if (utils.isInteger(by)) {
                            msg = skyMsgAlarmMapper.getMsgById(((Map) retVal.get(0)).get("").toString());
                        }
                    }
                } else {
                    for (List<Map<String, Object>> list : retVal) {
                        for (Map<String, Object> map : list) {
                            if (map.containsKey("")) {
                                String by = map.get("").toString();
                                if (utils.isInteger(by)) {
                                    msg += skyMsgAlarmMapper.getMsgById(map.get("").toString());
                                }
                            }
                        }
                    }
                }
                if (msg != null && !msg.equals("") && !msg.equals("null")) {
                    msgAdd += name + ":" + msg + "\n";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.build(ResultEnum.SERVER_ERROR);
        }
        if ("".equals(msgAdd)) {

            if (procedure.equals("eSP_ChangeOrgCheck")) {
                return BaseResult.build(ResultEnum.SERVER_ERROR, "数据确认成功!");
            } else if (procedure.equals("eSP_ChangeOrgCancel")) {
                return BaseResult.build(ResultEnum.SERVER_ERROR, "取消确认成功!");
            } else if (procedure.equals("eSP_ChangeOrgStart")) {
                return BaseResult.build(ResultEnum.SERVER_ERROR, "执行变动成功!");
            }
            return BaseResult.build(ResultEnum.SUCCESS);
        } else {
            return BaseResult.build(19970926, msgAdd, null);
        }
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<Map<String, Object>> historyList(Map map, Authority authority) {
        return depChangeMapper.historyList(map, authority);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public int removeLargeTwoMonths() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        int count = 0;
        try {
            //1.先取出所有入职登记的数据(还没有确认检查),取出每个登记时间的第二个月作为过期日期
            //2.取出当前时间,再拿后两个月的数据和当前时间比较,如果后者大于前者，则删除
            List<Map<String, Object>> empDataList = depChangeMapper.findEmpDataAll();
            for (Map map : empDataList) {
                //循环取出每一条记录的过期日期
                String expirationDate = depChangeMapper.expirationDate(map.get("RegDate").toString());
                //取出当前日期,如果当前日期比过期日期大，则删除
                String currentDate = df.format(new Date());
                if (df.parse(currentDate).after(df.parse(expirationDate))) {
                    //如果当前日期比过期日期大,则过期,即删除
                    String id = map.get("id").toString();
                    count += depChangeMapper.removeDepChange(id);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
}
